package com.buddha.api.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtUtils {

    private long expire;
    private String security;
    private String header;


    public String generateToken(String username){
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + 1000 * expire);
        String jwt = Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setSubject(username)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS512, security)
                .setExpiration(expireDate)
                .compact();
        return jwt;
    }



    public Claims getClaimByToken(String jwt){
         try {
             return Jwts.parser()
                     .setSigningKey(security)
                     .parseClaimsJws(jwt)
                     .getBody();
         }catch (Exception e){
            return null;
         }
    }

    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
